﻿#include "ltcSendAndReceivePlugin.h"
#include <QWidget>
#include <QTimeEdit>
#include <QVBoxLayout>
#include <QLabel>
#include <QDebug>
#include "LtcGenerator.h"
#include "LTCParser.h"

#include <Windows.h>
#include <Mmdeviceapi.h>
#include <Audioclient.h>


ltcSendAndReceivePlugin::ltcSendAndReceivePlugin()
{

}

QString ltcSendAndReceivePlugin::createPluginMenu()
{
	return "Tool/LTC";
}

void ltcSendAndReceivePlugin::createPluginMenuResult(bool result, QString menuId, QString error)
{

}

QWidget* ltcSendAndReceivePlugin::createPluginWidget()
{
	//{
 //       CoInitialize(NULL); // 初始化COM环境‌:ml-citation{ref="7" data="citationList"}
 //       HRESULT hr;
 //       IMMDeviceEnumerator* pEnumerator = nullptr;
 //       UINT32 bufferSize;

 //       // 创建设备枚举器
 //       hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL,
 //           CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
 //           (void**)&pEnumerator);
 //       if (FAILED(hr)) { /* 错误处理 */ }

 //       // 获取默认音频输入设备（麦克风）
 //       IMMDevice* pDevice = nullptr;
 //       hr = pEnumerator->GetDefaultAudioEndpoint(eCapture, eConsole, &pDevice);
 //       if (FAILED(hr)) { /* 错误处理 */ }

 //       IAudioClient* pAudioClient = nullptr;
 //       hr = pDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL,
 //           NULL, (void**)&pAudioClient);
 //       if (FAILED(hr)) { /* 错误处理 */ }

 //       // 设置音频格式（PCM 16bit 44.1kHz 双声道）
 //       WAVEFORMATEX desiredFormat = { 0 };
 //       desiredFormat.wFormatTag = WAVE_FORMAT_PCM;
 //       desiredFormat.nChannels = 2;
 //       desiredFormat.nSamplesPerSec = 44100;
 //       desiredFormat.wBitsPerSample = 16;
 //       desiredFormat.nBlockAlign = (desiredFormat.nChannels * desiredFormat.wBitsPerSample) / 8;
 //       desiredFormat.nAvgBytesPerSec = desiredFormat.nSamplesPerSec * desiredFormat.nBlockAlign;

 //       // 初始化音频客户端
 //       hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
 //           10000000, 0, &desiredFormat, NULL);
 //       if (FAILED(hr)) { /* 错误处理 */ }
	////}

	////{
 //       // 获取缓冲区大小
 //       UINT32 bufferFrameCount;
 //       hr = pAudioClient->GetBufferSize(&bufferFrameCount);
 //       if (FAILED(hr)) { /* 错误处理 */ }

 //       // 启动音频流
 //       hr = pAudioClient->Start();
 //       if (FAILED(hr)) { /* 错误处理 */ }

 //       // 获取音频渲染客户端（写入数据的关键接口）
 //       IAudioCaptureClient* pRenderClient = nullptr;
 //       hr = pAudioClient->GetService(__uuidof(IAudioCaptureClient),
 //           (void**)&pRenderClient); 
 //       if (FAILED(hr)) { 
 //           if (hr == E_POINTER)
 //           {
 //               qInfo() << "E_POINTER";
 //           }
 //           else if (hr == E_NOINTERFACE)
 //           {
 //               qInfo() << "E_NOINTERFACE";
 //           }
 //           else if (hr == AUDCLNT_E_NOT_INITIALIZED)
 //           {
 //               qInfo() << "AUDCLNT_E_NOT_INITIALIZED";
 //           }
 //           else if (hr == AUDCLNT_E_WRONG_ENDPOINT_TYPE)
 //           {
 //               qInfo() << "AUDCLNT_E_WRONG_ENDPOINT_TYPE";
 //           }
 //           else if (hr == AUDCLNT_E_DEVICE_INVALIDATED)
 //           {
 //               qInfo() << "AUDCLNT_E_DEVICE_INVALIDATED";
 //           }
 //           else if (hr == AUDCLNT_E_SERVICE_NOT_RUNNING)
 //           {
 //               qInfo() << "AUDCLNT_E_SERVICE_NOT_RUNNING";
 //           }
 //       }

 //       // 生成示例音频（1kHz正弦波）
 //       const int durationSec = 5;
 //       const int totalSamples = 44100 * durationSec * 2; // 双声道
 //       //BYTE* pData;
 //       //hr = pRenderClient->GetBuffer(bufferFrameCount, &pData);
 //       //for (int i = 0; i < totalSamples; i += bufferFrameCount) {
 //       //    // 填充正弦波数据到pData
 //       //    // (此处需实现具体的音频生成逻辑，例如PCM编码的LTC信号)

 //       //    hr = pRenderClient->ReleaseBuffer(bufferFrameCount, 0);
 //       //    if (FAILED(hr)) { /* 错误处理 */ }
 //       //}


	////}

	QWidget* w = new QWidget;
	QVBoxLayout* layout = new QVBoxLayout(w);
	{
		QLabel* senderLabel = new QLabel("Sender", w);
		QTimeEdit* senderTimeEdit = new QTimeEdit(w);
		QHBoxLayout* senderLayout = new QHBoxLayout;
		senderLayout->addWidget(senderLabel);
        senderLayout->addWidget(senderTimeEdit);
		layout->addLayout(senderLayout);
	}

	{
		QLabel* revLabel = new QLabel("Receiver", w);
		QTimeEdit* revTimeEdit = new QTimeEdit(w);
		revTimeEdit->setDisplayFormat("hh:mm:ss");
		QHBoxLayout* revLayout = new QHBoxLayout;
		revLayout->addWidget(revLabel);
		revLayout->addWidget(revTimeEdit);
		layout->addLayout(revLayout);

        LTCParser *ltcParser = new LTCParser;
		connect(ltcParser, &LTCParser::timeMsecOccurred, this, [this, revTimeEdit](qint64 msec) {
			qInfo() << tr("Receive LTC Time: ") << QTime::fromMSecsSinceStartOfDay(msec).toString("hh:mm:ss.zzz");
			revTimeEdit->setTime(QTime::fromMSecsSinceStartOfDay(msec));
		});
		LtcGenerator *ltcGenerator = new LtcGenerator;
		connect(ltcGenerator, &LtcGenerator::productionOccurred, this, [this,ltcParser/*, pAudioClient, bufferFrameCount, pRenderClient*/](const QByteArray& buff) {
			ltcParser->parse(buff);
            //size_t pos = 0;
            //UINT32 padding;
            //BYTE* pBuffer;
            //while (pos < buff.size()) {
            //    pAudioClient->GetCurrentPadding(&padding);
            //    UINT32 available = bufferFrameCount - padding;
            //    if (available > 0)
            //    {
            //        UINT32 writeSize = qMin<UINT32>(available, (UINT32)(buff.size() - pos));
            //        pRenderClient->GetBuffer(writeSize, &pBuffer);

            //        // 将浮点数据复制到缓冲区
            //        memcpy(pBuffer, &buff.data()[pos], writeSize * sizeof(float));
            //        pRenderClient->ReleaseBuffer(writeSize, 0);
            //        pos += writeSize;
            //    }
            //}
		});
	}
	
	layout->addStretch(1);
	return w;
}

void ltcSendAndReceivePlugin::destroyPluginWidget()
{

}

